﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;

namespace PWAsker
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public const String PW_REGEX = "%PW%";
        public const String CONFIGFILE = "settings.xml";

        xml_handler config;
        List<String> executables;

        public MainWindow()
        {
            //TODO: Spwn window in center of the screen
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs eventArgs)
        {
            String SzExecString;

            if (config == null)
            {
                config = new xml_handler(CONFIGFILE);
            }
            if (executables == null)
            {
                executables = config.getCommands();
            }
            
            //Executing commands
            for (int i = 0; i < executables.Count; i++)
            {
                SzExecString = replaceRegex(executables.ElementAt(i), passwordBox1.Password);

                Debug.WriteLine("Replaced " + executables.ElementAt(i) + " with " + SzExecString);

                shellExecute(SzExecString);
            }
        }

        private void button2_Click(object sender, RoutedEventArgs eventArgs)
        {
            bool bFileLoad = true;
            
            try
            {
                List<String> executables = config.getCommands();
                bFileLoad = true;
            }
            catch (System.NullReferenceException)
            {
                bFileLoad = false;
                if (System.Windows.Forms.MessageBox.Show("Configuration-file is currently not loaded. Load it now?", "Configfile not loaded", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Asterisk) == System.Windows.Forms.DialogResult.Yes)
                {
                    config = new xml_handler(CONFIGFILE);
                    executables = config.getCommands();
                    bFileLoad = true;
                }
            };
            if (bFileLoad)
            {
                Debug.WriteLine("Starting configuration window");
                
                Debug.WriteLine("executables before config");
                debugDumpList(executables);

                ConfigurationWnd confWnd = new ConfigurationWnd(ref executables);
                confWnd.Owner = this;
                confWnd.ShowDialog();

                Debug.WriteLine("executables after config");
                debugDumpList(executables);

                if (confWnd.madeChanges())
                {
                    Debug.WriteLine("configuration changed. Rewriting xml-file");
                    config.writeFile(executables);
                }
                else
                {
                    Debug.WriteLine("No changes in cofiguration detected. No need rewriting xml-file");
                }

            }
        }

        private void shellExecute(String szCommand)
        {
            String szFilename = separateFilename(szCommand);
            String szArgs = szCommand.Substring(szFilename.Length);
            
            Debug.WriteLine("Executing file: "+szFilename + " with argument " +  szArgs);
            System.Diagnostics.Process cmd = new System.Diagnostics.Process();
            cmd.EnableRaisingEvents = false;
            cmd.StartInfo.FileName = szFilename;
            cmd.StartInfo.Arguments = szArgs;
            try
            {
                cmd.Start();
            }
            catch (System.ComponentModel.Win32Exception)
            {
                MessageBox.Show("File '" + szFilename + "' not found");
            };
        }

        private String separateFilename(String szCommand)
        {
            String stRet;
            int n;

            if(szCommand.ElementAt(0) == '"')
            {
                for(n = 1; n<szCommand.Length;n++)
                {
                    if (szCommand.ElementAt(n) == '"')
                    {
                        return szCommand.Substring(0, n);
                    };
                };
            }
            return szCommand.Split(' ')[0];   
        }

        private string replaceRegex(String szString, String szPassword)
        {
            
            for (int i = 0; i < szString.Length; i++)
            {
                if (szString.ElementAt(i) == PW_REGEX.ElementAt(0))
                {

                    for (int c = 0; c<PW_REGEX.Length; c++)
                    {
                        if (szString.ElementAt(i + c) != PW_REGEX.ElementAt(c))
                        {
                            break;
                        }
                        if (c == PW_REGEX.Length - 1)
                        {
                            String szTmp;

                            szTmp = szString.Substring(0, i);
                            szString = szString.Substring(i + c+1);
                            
                            szTmp = szTmp + szPassword;
                            szString = szTmp + szString;
                            
                            i = i + (szPassword.Length - PW_REGEX.Length);
                        }

                    }
                }
            }
            return szString;
        }
        private void debugDumpList(List<String> szList)
        { 
            for (int i = 0; i < szList.Count; i++)
            {
                Debug.WriteLine(szList.ElementAt(i));
            }

            Debug.WriteLine("------------------------");
        }
    }
}
